package crypto.testSource;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.IOException;

import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * DOCUMENT ME!
 *
 * @author gato
 */
public class XMLReader {
  /**
   * DOCUMENT ME!
   *
   * @param path DOCUMENT ME!
   *
   * @return DOCUMENT ME!
   */
  public static String readTextFile(String path) {
    StringBuffer sb = new StringBuffer();

    try {
      BufferedReader in  = new BufferedReader(new FileReader(path));

      String         str;

      while ((str = in.readLine()) != null) {
        sb.append(str);
      }

      in.close();
    } catch (IOException e) {
      e.printStackTrace();

      return "";
    }

    return sb.toString();
  }

  /**
   * DOCUMENT ME!
   *
   * @param str DOCUMENT ME!
   * @param arrayParam DOCUMENT ME!
   *
   * @return DOCUMENT ME!
   */
  public static Vector fromXml(String str, String[] arrayParam) {
    ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());

    try {
      DocumentBuilderFactory fact   = DocumentBuilderFactory.newInstance();
      DocumentBuilder        parser = fact.newDocumentBuilder();
      Document               doc    = parser.parse(is);

      return fromXml(doc, arrayParam);
    } catch (Exception ex) {
      ex.printStackTrace();

      return null;
    }
  }

  /**
   * DOCUMENT ME!
   *
   * @param doc DOCUMENT ME!
   * @param arrayParam DOCUMENT ME!
   *
   * @return DOCUMENT ME!
   */
  public static Vector fromXml(Document doc, String[] arrayParam) {
    Vector vector = new Vector();

    for (int i = 0; i < arrayParam.length; i++) {
      vector.addElement(new Vector());

      try {
        NodeList nodes     = doc.getElementsByTagName(arrayParam[i]);

        int      cantNodes = nodes.getLength();

        for (int j = 0; j < cantNodes; j++) {
          Node data = nodes.item(j);

          try {
            String dataString = data.getFirstChild().getNodeValue();

            ((Vector) vector.get(i)).addElement(dataString);
          } catch (Exception e) {
            e.printStackTrace();

            return null;
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();

        return null;
      }
    }

    return vector;
  }
}
